﻿@{
    ViewBag.Title = "添加退货通知单";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>添加退货通知单</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 15px;
        }
        /* 表单行样式 */
        .layui-form-item {
            margin-bottom: 15px;
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 15px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
            margin-top: 15px;
        }
            /* 表格中的输入框样式 */
            .layui-table td .layui-input {
                border: 1px solid #e6e6e6;
            }
        /* 选择物料按钮样式 */
        .selectMaterialButton {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn" id="saveButton">保存</button>
        </div>
        <!-- 表单信息 -->

        <form class="layui-form" action="">
            <div class="layui-form-item layui-row layui-col-space10">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据编码</label>
                    <div class="layui-input-block">
                        <input type="text" name="document_code" placeholder="自动生成" class="layui-input" id="document_code" readonly>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">业务类型</label>
                    <div class="layui-input-block">
                        <select name="business_type_id" id="business_type_id" lay-verify="required">
                            <option value="普通退货">普通退货</option>
                            <option value="直运退货">直运退货</option>
                            <!-- 可根据实际业务添加更多选项 -->
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">客户名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="customer_name" id="customer_name" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">仓库</label>
                    <div class="layui-input-block">
                        <select name="warehouse_id" id="warehouse_id" lay-verify="required">
                            <option value="1">成品仓</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-row layui-col-space10">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据日期</label>
                    <div class="layui-input-block">
                        <input type="date" name="document_date" id="document_date" value="2025-03-28" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">操作员</label>
                    <div class="layui-input-block">
                        <input type="text" name="operators" id="operators" value="njrsun" class="layui-input" disabled>
                    </div>
                </div>


            </div>

            <div class="layui-form-item layui-row layui-col-space10">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据状态</label>
                    <div class="layui-input-block">
                        <select name="document_status" id="document_status" lay-verify="required">
                            <option value="开立">开立</option>
                            <option value="审核">审核</option>
                            <!-- 可添加其他业务状态选项 -->
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">审核员</label>
                    <div class="layui-input-block">
                        <input type="text" name="auditor" id="auditor" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">退货原因</label>
                    <div class="layui-input-block">
                        <select name="return_reason_code" id="return_reason_code" lay-verify="required">
                            <option value="外观问题">外观问题</option>
                            <option value="质量问题">质量问题</option>
                            <!-- 可添加其他税率选项 -->
                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-row layui-col-space10">
                <div class="layui-col-md3">
                    <label class="layui-form-label">业务状态</label>
                    <div class="layui-input-block">
                        <select name="business_status_id" id="business_status_id" lay-verify="required">
                            <option value="1">正常</option>
                            <option value="2">挂起</option>
                            <option value="3">手工关闭</option>
                            <option value="4">系统关闭</option>
                            <!-- 可添加其他业务状态选项 -->
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">审核日期</label>
                    <div class="layui-input-block">
                        <input type="date" name="audit_date" id="audit_date" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">处理方式</label>
                    <div class="layui-input-block">
                        <select name="handling_method_code" id="handling_method_code" lay-verify="required">
                            <option value="无">无</option>
                            <option value="计划生产">计划生产</option>
                            <!-- 可添加其他业务状态选项 -->
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">备注信息</label>
                    <div class="layui-input-block">
                        <textarea name="remark" id="remark" class="layui-textarea" placeholder="请输入备注信息"></textarea>
                    </div>
                </div>
            </div>
        </form>

       


        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            @* <button class="layui-btn layui-btn-xs" id="importButton">引入</button> *@
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
        </div>

        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>主计量</th>
                    <th>数量</th>
                    <th>单价</th>
                    <th>金额</th>
                    <th>件数</th>
                    <th>质量要求</th>
                    <th>包装要求</th>
                    <th>备注</th>
                    <th>批次</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                @*  <tr>
                <td>1</td>
                <td><input type="text" id="materialsCode" value="0400000002" class="layui-input" placeholder="请添加物料" readonly><button class="layui-btn layui-btn-xs" class="selectMaterialButton">选择</button></td>
                <td><input type="text" id="materialsName" value="物料1" class="layui-input" readonly /></td>
                <td><select class="layui-select" id="color"><option value="白色">白色</option><option value="黑色">黑色</option></td>
                <td><select class="layui-select" id="calulate"><option value="台">台</option><option value="箱">箱</option></select></td>
                <td><input type="text" id="calulateNumber" class="layui-input" placeholder="请输入数量"></td>
                <td><input type="text" class="layui-input" value="0.00" id="price" placeholder="请输入单价"></td>
                <td><input type="text" class="layui-input" value="0.00" id="totalPrice" placeholder="请输入金额"></td>
                <td><input type="text" id="calulateNumber" class="layui-input" placeholder="件数"><select class="layui-select" id="calulate"><option value="台">台</option><option value="箱">箱</option></select></td>
                <td><input type="text" class="layui-input" placeholder="请输入质量要求" id="qualityRequir"></td>
                <td><input type="text" class="layui-input" placeholder="请输入包装要求" id="packRequir"></td>
                <td><input type="text" class="layui-input" placeholder="请输入备注" id="remark"></td>
                <td><button class="layui-btn layui-btn-xs layui-btn-danger" class="deleteMaterialButton">删除</button></td>
                </tr> *@
            </tbody>
        </table>
    </div>

    @*  //在html代码中添加一个隐藏的模版，用于展示物料清单表格 *@
    <script type="text/html" id="materialListTemplate">
        <div style="padding: 10px;">
            <table class="layui-table" id="materialListTable">
                <thead>
                    <tr>
                        <th>物料编码</th>
                        <th>物料名称</th>
                        <th>型号规格</th>
                        <th>主计量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </script>

    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;

            // 初始化一个空行
            function initEmptyRow() {
                return {
                    materialsCode: '',
                    materialsName: '苏云建的物料',
                    modelSpecification: '',
                    color: '',
                    calulate: '箱',
                    calulateNumber: 0,
                    outBoundNumber: 0,
                    volume: 0,
                    batch: '',
                    price: 0,
                    totalPrice: 0,
                    qualityRequir: '',
                    packRequir: '',
                    remark: '',
                    materialsClass: 8
                };
            }

            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml = `
                                                        <tr data-index="${rowCount - 1}">
                                                            <td>${rowCount}</td>
                                                            <td>
                                                                        <input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="物料编码" readonly>
                                                                <button type="button" class="layui-btn layui-btn-xs selectMaterialButton">选择</button>
                                                            </td>
                                                                    <td><input type="text" class="layui-input materialsName" value="${material.materialsName}" id="materialsName" placeholder="物料名称" readonly></td>
                                                                                    <td><input type="text" class="layui-input" value="${material.modelSpecification}" id="modelSpecification" placeholder="型号规格"></td>
                                                            <td>
                                                                        <select class="layui-select calulate" id="calulate">
                                                                    <option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option>
                                                                            <option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option>
                                                                            <option value="只" ${material.calulate === '只' ? 'selected' : ''}>只</option>
                                                                </select>
                                                            </td>
                                                                    <td><input type="number" class="layui-input calulateNumber" id="calulateNumber" value="${material.calulateNumber}" placeholder="数量"></td>
                                                                    <td><input type="number" class="layui-input price" id="price" value="${material.price}" placeholder="单价"></td>
                                                                    <td><input type="number" class="layui-input totalPrice" id="totalPrice" value="${material.totalPrice}" placeholder="金额" readonly></td>
                                                                    <td><input type="number" class="layui-input outBoundNumber" id="outBoundNumber" value="${material.outBoundNumber}" placeholder="件数"></td>
                                                                    <td><input type="text" class="layui-input qualityRequir" id="qualityRequir" value="${material.qualityRequir}" placeholder="质量要求"></td>
                                                                    <td><input type="text" class="layui-input packRequir" id="packRequir" value="${material.packRequir}" placeholder="包装要求"></td>
                                                                            <td><input type="text" class="layui-input remark" id="remark" value="${material.remark}" placeholder="备注"></td>
                                                                                            <td><input type="text" class="layui-input remark" id="batch" value="${material.batch}" placeholder="批号"></td>
                                                            <td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button></td>
                                                        </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }

        

            // 保存按钮点击事件
            $('#saveButton').click(function () {
                var formData = {
                    document_code: $('#document_code').val() || generateUUID(),
                    document_date: $('#document_date').val(),
                    business_type_id: $('#business_type_id').val(),
                    warehouse_id: $('#warehouse_id').val(),
                    operators: $('#operators').val(),
                    customer_name: $('#customer_name').val(),
                    document_status: $('#document_status').val(),
                    auditor: $('#auditor').val(),
                    audit_date: $('#audit_date').val(),
                    business_status_id: $('#business_status_id').val(),
                    return_reason_code: $('#return_reason_code').val(),
                    handling_method_code: $('#handling_method_code').val(),
                    remark: $('#remark').val(),
                    orderMaterials: []
                };
                console.log(formData);
                // 收集物料数据
                $('#materialTable tbody tr').each(function () {
                    var $tr = $(this);
                    var material = {
                        materialsCode: $tr.find('#materialsCode').val(),
                        materialsName: $tr.find('#materialsName').val(),
                        modelSpecification: $tr.find('#modelSpecification').val(),
                        color: $tr.find('#color').val(),
                        calulate: $tr.find('#calulate').val(),
                        calulateNumber: parseFloat($tr.find('#calulateNumber').val()),
                        outBoundNumber: parseFloat($tr.find('#outBoundNumber').val()),
                        volume: 0, // 可根据需要计算--体积
                        batch: $tr.find('#batch').val(), // 可根据需要填写--批号
                        price: parseFloat($tr.find('#price').val()),
                        totalPrice: parseFloat($tr.find('#totalPrice').val()),
                        qualityRequir: $tr.find('#qualityRequir').val(),
                        packRequir: $tr.find('#packRequir').val(),
                        remark: $tr.find('#remark').val(),
                        materialsClass: 8 // 默认分类
                    };
                    formData.orderMaterials.push(material);
                });


                if (formData.orderMaterials.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }

                var loadIndex = layer.load(2);
                console.log("查看添加参数", formData);
                $.ajax({
                    //url: 'http://localhost:5090/api/Sales/Addreturn_notice_main',
                    url: "@ViewBag.BaseUrl/T8/Sales/Addreturn_notice_main",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 212) {
                            layer.msg(res.msg, { icon: 7 }, function () {
                                // 保存成功后可以跳转或刷新页面
                                $('#document_code').val(formData.id);
                                location.href = "/Sales/Getreturn_notice_main"
                            });
                        } else {
                            layer.msg(res.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            });

            // 生成UUID
            function generateUUID() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c === 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }

            // 计算金额
            $(document).on('change', '.calulateNumber, .price', function () {
                var $tr = $(this).closest('tr');
                var quantity = parseFloat($tr.find('.calulateNumber').val()) || 0;
                var price = parseFloat($tr.find('.price').val()) || 0;
                var total = quantity * price;
                $tr.find('.totalPrice').val(total.toFixed(2));
            });




            //物料弹出框
            function showMaterialList() {
                layer.open({
                    type: 1,
                    title: '选择物料',
                    area: ['800px', '500px'],
                    content: $('#materialListTemplate').html(), // 假设后面会创建一个物料清单模板
                    success: function (layero) {
                        // 调用接口获取物料数据
                        $.ajax({
                            //url: 'http://localhost:5234/api/Materials/GetMaterial_Basic',
                            url: "@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic",
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 0) {
                                    var materialList = res.data;
                                    var tableBody = $('#materialListTable tbody');
                                    tableBody.empty();
                                    materialList.forEach(function (material) {
                                        var row = $('<tr>');
                                        row.append($('<td>').text(material.material_code));
                                        row.append($('<td>').text(material.material_name));
                                        row.append($('<td>').text(material.model_specification));
                                        row.append($('<td>').text(material.unit_of_measurement_name));
                                        row.append($('<td>').html('<button class="layui-btn layui-btn-xs selectMaterialConfirm">确认</button>'));
                                        row.data('material', material);
                                        tableBody.append(row);
                                    });
                                    form.render();
                                } else {
                                    layer.msg(res.msg || '获取物料数据失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('请求失败: ' + error, { icon: 2 });
                                console.error(xhr.responseText);
                            }
                        });
                    }
                });
            }
            // 初始化一个空行
            addMaterialRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });

            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', {
                    btn: ['确定', '取消'] // 按钮文本
                }, function (index) { // 点击确定后的回调
                    $tr.remove();
                    // 重新编号
                    $('#materialTable tbody tr').each(function (index) {
                        $(this).find('td:first').text(index + 1);
                    });
                    layer.close(index); // 关键：关闭当前弹窗
                }, function (index) {
                    layer.close(index); // 取消时也关闭弹窗
                });
            });
            //选择按钮绑定点击事件
            $(document).on('click', '.selectMaterialButton', function () {
                showMaterialList();
            });
            //处理"确定选择"按钮后的回填操作
            $(document).on('click', '.selectMaterialConfirm', function () {
                var material = $(this).closest('tr').data('material');
                var currentRow = $('#materialTable tbody tr:last'); // 获取当前最后一行表格
                currentRow.find('#materialsCode').val(material.material_code);
                currentRow.find('#materialsName').val(material.material_name);
                currentRow.find('#modelSpecification').val(material.model_specification);
                var unit = material.unit_of_measurement_name;
                currentRow.find('#calulate option').each(function () {
                    if ($(this).text() === unit) {
                        $(this).prop('selected', true);

                    }
                });
                form.render();
                layer.closeAll('page'); // 关闭物料清单弹窗
            });



        });
    </script>
</body>
</html>